<template>
  <div :class="{ left: isShow, right: !isShow }" @click="backtop" id="backtop">
    <qm-icon class="aicon" name="icon-top"></qm-icon>
  </div>
</template>

<script>
export default {
  name: 'backTop',
  mounted() {
    window.addEventListener('scroll', this.scrollListener)
  },
  props: {
    h: {
      type: Number,
      default: 200
    },
    time: {
      type: Number,
      default: 2000
    }
  },
  data() {
    return {
      isShow: false
    }
  },
  methods: {
    backtop() {
      let top = document.documentElement.scrollTop
      const timeTop = setInterval(() => {
        const v = 30000 / this.time <= 0 ? 10 : 30000 / this.time
        document.body.scrollTop = document.documentElement.scrollTop = top -= v
        if (top <= 0) {
          clearInterval(timeTop)
        }
      }, 1)
    },
    scrollListener() {
      let html = document.documentElement
      if (html.scrollTop >= this.h) {
        this.isShow = true
      } else {
        this.isShow = false
      }
    }
  },
  beforeUnmount() {
    window.removeEventListener('scroll', this.scrollListener)
  }
}
</script>

<style lang="less" scoped>
#backtop {
  position: fixed;
  bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 40px;
  color: @fbtnfc;
  background: @fbtnc;
  border-radius: 8px;
  opacity: 1;
}

.left {
  right: 20px !important;
  transition: all 0.8s;
}

.right {
  right: -50px !important;
  transition: all 0.8s;
}

.icon {
  width: 100%;
  height: 100%;
}
</style>
